<template>
  <div>
    <div style="display: flex; align-items: center; padding: 10px; color: #fff;">
      <span style="margin-right: 20px; font-weight: bold;">精准靶向服务产品</span>
      <span style="margin-right: 20px;">|</span>
      <span style="display: flex; align-items: center;">
        <span>地灾点雨量</span>
      </span>
    </div>

    <div style="padding: 10px; color: #fff; display: flex; align-items: center;">
      <!-- <el-date-picker
        v-model="date"
        type="datetime"
        placeholder="选择日期时间"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="margin-right: 10px;"
        class="el-date-picker"
      >
      </el-date-picker> -->

      <el-select v-model="selectedDistrict" @change="handleDistrictChange" placeholder="全市" style="margin-right: 20px;" class="custom-select">
            <el-option label="全部" value="all-types"></el-option>
            <el-option
              v-for="district in uniqueDistricts"
              :key="district"
              :label="district"
              :value="district">
            </el-option>
          </el-select>

          <el-select v-if="selectedDistrict !== 'all-types'" v-model="selectedTownship" @change="fetchData" placeholder="选择街区" style="margin-right: 20px;" class="custom-select">
            <el-option label="全部街区" value="all-townships"></el-option>
            <el-option
              v-for="township in uniqueTownships"
              :key="township"
              :label="township"
              :value="township">
            </el-option>
          </el-select>

          <el-select v-model="selectedPrecipitation" @change="fetchData" placeholder="全部类型" class="custom-select">
            <el-option label="全部类型" value="all-types"></el-option>
            <el-option
              v-for="type in uniqueTypes"
              :key="type"
              :label="type"
              :value="type" >
            </el-option>
          </el-select>

          <div class="time" style="margin-left: 20px;">
          预报时间: <span>{{ forecastTime }}</span> 实况最新分钟时间: <span>{{ currentTime }}</span>
        </div>

    </div>

    <el-table
      :data="filteredData"
      style="width: 100%"
      stripe
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <el-table-column prop="serialNumber" label="序号" width="73" />
      <el-table-column prop="hiddenPointName" label="隐患点名称" width="200" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="district" label="区县" />
      <el-table-column prop="township" label="乡镇" />
      <el-table-column prop="village" label="村" width="70" />
      <el-table-column prop="group" label="组" width="70" />
      <el-table-column prop="nearestWeatherStation" label="最近气象站" />
      <el-table-column prop="distance" label="距离" />
      <el-table-column prop="oneHourRainfall" label="1小时雨量" />
      <el-table-column prop="twoHourRainfall" label="2小时雨量" />
      <el-table-column prop="threeHourRainfall" label="3小时雨量" />
      <el-table-column prop="sixHourRainfall" label="6小时雨量" />
      <el-table-column prop="twelveHourRainfall" label="12小时雨量" />
      <el-table-column prop="minuteRainfall" label="分钟雨量" />
      <el-table-column prop="oneHourForecast" label="1h预报" />
    </el-table>
    
    <el-dialog :visible.sync="dialogVisible" :title="`隐患点名称： ${selectedRow ? selectedRow.hiddenPointName : ''}`">
      <div v-if="contacts.length">
        <h3>隐患点联系人</h3>
        <el-table :data="contacts" stripe>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="tel" label="电话" width="150"></el-table-column>
          <el-table-column prop="county" label="区县"></el-table-column>
          <el-table-column prop="town" label="乡镇"></el-table-column>
          <el-table-column prop="village" label="乡村"></el-table-column>
          <el-table-column prop="street" label="街道"></el-table-column>
          <el-table-column prop="position" label="职位--职责" width="130"></el-table-column>
          <el-table-column prop="confirm" label="回执"></el-table-column>
        </el-table>
      </div>
      <div v-else>
        <p>未查询到隐患点联系人信息</p>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Cookies from 'js-cookie';
import Request from "@/utils/request";

export default {
  data() {
    return {
      county:Cookies.get('county'),
      loading: true,
      forecastTime: '',
      currentTime: '',
      selectedDistrict: 'all-types',
      selectedTownship: 'all-townships',
      selectedPrecipitation: 'all-types',
      tableData: [],
      currentPage: 1,
      pageSize: 99999,
      totalRecords: 0,
      uniqueDistricts: [],
      uniqueTownships: [],
      uniqueTypes: [],
      dialogVisible: false,
      selectedRow: null,
      contacts: [],
      disasterId: '' 
    };
  },
  computed: {
    filteredData() {
      return this.tableData.filter(item => {
        return (this.selectedDistrict === 'all-types' || item.district === this.selectedDistrict) &&
               (this.selectedTownship === 'all-townships' || item.township === this.selectedTownship) &&
               (this.selectedPrecipitation === 'all-types' || item.type === this.selectedPrecipitation) &&
               (item.type !== '山洪沟'); 
      });
    }
  },
  methods: {
    updateTime() {
      const now = new Date();
      const forecast = new Date(now.getTime() - 30 * 60 * 1000);

      this.forecastTime = forecast.toLocaleString('zh-CN', { hour12: false });
      this.currentTime = now.toLocaleString('zh-CN', { hour12: false });
    },
    fetchData() {
      this.loading = true;
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        isTravel:false
      };
      Request.get('/precisetarget/listOfRainOfGeology', { params })
        .then(response => {
          if (response.status === 200 && response.data.code === 200) {
            const records = response.data.data.records;
            this.tableData = records
              .filter(record => record.type !== '山洪沟')
              .map((record, index) => ({
                serialNumber: (this.currentPage - 1) * this.pageSize + index + 1,
                hiddenPointName: record.dsname,
                type: record.type,
                district: record.county,
                township: record.town,
                village: record.village,
                group: record.street,
                nearestWeatherStation: record.meteorologicalStation,
                distance: record.distance,
                oneHourRainfall: record.rain1h,
                twoHourRainfall: record.rain2h,
                threeHourRainfall: record.rain3h,
                sixHourRainfall: record.rain6h,
                twelveHourRainfall: record.rain12h,
                minuteRainfall: record.rainMinute,
                oneHourForecast: record.rain1hYb,
                disasterId: record.disasterId 
              }));
            this.totalRecords = response.data.data.total;
            this.extractUniqueDistricts(records);
            this.extractUniqueTypes(records); 
            this.updateUniqueTownships();
          } else {
            this.$message.error(`Error: ${response.data.msg}`);
          }
          this.loading = false;
        })
        .catch(error => {
          this.$message.error(`Request failed: ${error}`);
          this.loading = false;
        });
    },
    extractUniqueDistricts(records) {
      const districts = records.map(record => record.county);
      this.uniqueDistricts = [...new Set(districts)];
    },
    extractUniqueTypes(records) {
      const types = records
        .map(record => record.type)
        .filter(type => type !== '山洪沟');
      this.uniqueTypes = [...new Set(types)];
    },
    updateUniqueTownships() {
      if (this.selectedDistrict === 'all-types') {
        this.uniqueTownships = [];
        return;
      }
      const townships = this.tableData
        .filter(record => record.district === this.selectedDistrict)
        .map(record => record.township);
      this.uniqueTownships = [...new Set(townships)];
    },
    handleDistrictChange() {
     this.selectedTownship = 'all-townships';
     this.updateUniqueTownships();
     this.fetchData();
    },

    handlePageChange(page) {
      this.currentPage = page;
      this.fetchData();
    },
    handleRowClick(row) {
      this.selectedRow = row;
      this.disasterId = row.disasterId; 
      this.fetchContactsFromAPI(this.disasterId); 
      this.dialogVisible = true;
    },
    fetchContactsFromAPI(disasterId) {
      Request.get(`/precisetarget/hazardContact/${disasterId}`)
        .then(response => {
          if (response.status === 200) {
            this.contacts = response.data.data;
            console.log(this.contacts)
          } else {
            this.$message.error(`Error fetching contacts: ${response.data.msg}`);
          }
        })
        .catch(error => {
          this.$message.error(`Request failed: ${error}`);
        });
    },
    headerCellStyle() {
      return {
        background: '#0c2340',
        color: '#fff',
      };
    },
    cellStyle() {
      return {
        background: '#05152e',
        color: '#fff',
      };
    },
    rowStyle() {
      return {
        height: '30px',
      };
    },
  },
  mounted() {
    this.updateTime();
    this.fetchData();
  }
};
</script>

<style lang="less">
.custom-select .el-input__inner,
.el-date-picker .el-input__inner {
  background-color: rgb(36, 54, 101) !important; 
  color: white !important;
  font-weight: bold !important;
  border: 2px solid #fff !important;
}
</style>
